package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.exception.BusinessException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageBean;
import com.sky.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {


    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    //分类分页查询
    @Override
    public PageBean  findByPage(CategoryPageQueryDTO categoryPageQueryDTO) {
        //1.开启分页
        PageHelper.startPage(categoryPageQueryDTO.getPage(),categoryPageQueryDTO.getPageSize());
        //2.执行查询
        Page<Category> page = (Page<Category>) categoryMapper.findList(categoryPageQueryDTO);
        //3.返回结果
        return new PageBean(page.getTotal(),page.getResult());
    }

    //新增分类
    @Override
    public void save(Category category) {
        //1.补齐参数
        category.setStatus(1);//默认启用
        //2.执行保存
        categoryMapper.save(category);
    }

    //删除分类-->根据主键删除
    @Override
    public void deleteById(Long id) {
        //1. 根据分类id从菜品表中进行统计,如果统计数值>0,则进行提示
        int count1 = dishMapper.countByCategoryId(id);
        if (count1 > 0){
            throw new BusinessException("当前分类下存在菜品,无法删除");
        }

        //2. 根据分类id从套餐表中进行统计,如果统计数值>0,则进行提示
        int count2 = setmealMapper.countByCategoryId(id);
        if (count2 > 0){
            throw new BusinessException("当前分类下存在套餐,无法删除");
        }

        //3. 到达这一步可以直接执行删除
        categoryMapper.deleteById(id);
    }

    //修改分类
    @Override
    public void update(Category category) {
        categoryMapper.update(category);
    }

    //根据分类和状态查询
    @Override
    public List<Category> findByStatusAndType(Integer type) {
        //1. 封装dto
        CategoryDTO categoryDTO = CategoryDTO.builder()
                .status(1)
                .type(type)
                .build();
        return categoryMapper.findByStatusAndType(categoryDTO);
    }


}
